<template>
  <div>
    <h2>购物车</h2>
    <ul>
      <li v-for="item in cart" :key="item.id">
        {{ item.name }} - ¥{{ item.price }} 
        <button @click="decreaseQuantity(item.id)">－</button>
        <span>{{ item.quantity }}</span>
        <button @click="increaseQuantity(item.id)">＋</button>
      </li>
    </ul>
    <p>总价: ¥{{ totalPrice }}</p>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex'

export default {
  computed: {
    ...mapState(['cart']),
    ...mapGetters(['totalPrice'])
  },
  methods: {
    ...mapActions(['removeFromCart']),
    increaseQuantity(productId) {
      // 调用增加数量的action
      this.$store.dispatch('addToCart', this.cart.find(item => item.id === productId))
    },
    decreaseQuantity(productId) {
      // 调用减少数量的action（即原来的removeFromCart）
      this.$store.dispatch('removeFromCart', productId)
    }
  }
}
</script>

<style scoped>
button {
  margin: 0 5px;
  padding: 0 5px;
  min-width: 25px;
}
</style>